#include "World.hpp"
#include "WorldSession.hpp"
#include <memory>
#include <mutex>
#include "Player.hpp"
#include "Opcode.hpp"
#include "CSProto.hpp"

bool World::Init()
{
    return true;
}

bool World::Update(uint32_t diff)
{
    // new session
    {
        std::lock_guard<std::mutex> guard(_newSessionMutex);
        for(auto it : _newSessions)
        {
            _sessions.push_back(std::make_shared<Player>(std::move(it)));
        }
        _newSessions.clear();
    }

    for(auto it = _sessions.begin(); it != _sessions.end();)
    {
        if(!(*it)->Update(diff))
        {
            // remove
            (*it)->GetSession()->GetSocket()->CloseSocket();
            _sessions.erase(it++);
        }
        else
        {
            ++it;
        }
    }
    return true;
}

void World::Stop()
{
    // save and kick all player, send kick proto
}

void World::AddSession(std::shared_ptr<WorldSession>&& session)
{
    std::lock_guard<std::mutex> guard(_newSessionMutex);
    _newSessions.push_back(std::move(session));
}
